<?php

/**
 * purchase actions.
 *
 * @package    Porba
 * @subpackage purchase
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class purchaseActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
        //Purchases pager in descending order
        $this->pagerPurchases = new sfDoctrinePager('Purchase', sfConfig::get('app_max_items_on_page'));
        $this->pagerPurchases->setQuery(PurchaseTable::findAllDescQuery());
        $this->pagerPurchases->setPage($request->getParameter('pagepurchase', 1));
        $this->pagerPurchases->init();
        
        //Materials under minimum quantity pager
        $this->pagerMaterials = new sfDoctrinePager('Part', sfConfig::get('app_max_items_on_page'));
        $this->pagerMaterials->setQuery(PartTable::findUnderMinimumQuery());
        $this->pagerMaterials->setPage($request->getParameter('pagematerial', 1));
        $this->pagerMaterials->init();
        
        //filter
        $this->filterPurchase = new PurchaseFormFilter;
  }
  
  public function executeNewPurchase(sfWebRequest $request) {
        $this->form = new PurchaseForm();
        $this->version = 'cart';
        $this->materials = PartTable::findAboveMinimum();
        $this->needToPurchase = PartTable::findUnderMinimum();
            
        //Use new template for this action
        $this->setTemplate('new');
  }
    
  public function executeNewShoppingList(sfWebRequest $request) {
        $this->form = new PurchaseForm();
        $this->version = 'list';
        $this->materials = PartTable::findAboveMinimum();
        $this->needToPurchase = PartTable::findUnderMinimum();
            
        //Use new template for this action
        $this->setTemplate('new');
  } 
  
  public function executeNewClearList(sfWebRequest $request) {
        $this->form = new PurchaseForm();
        $this->version = 'clear';
        $this->purchases = PurchaseTable::getInstance()->findBy('status', 'ordered');
            
        //Use new template for this action
        $this->setTemplate('new');
  }
  
  public function executeShowShoppingList(sfWebRequest $request) {
      $this->setLayout(false);
      $this->version = 'shop';
      $this->setTemplate('show');
  }
  
  public function executeShowClearList(sfWebRequest $request) {
      $this->setLayout(false);
      $this->version = 'clear';
      $this->setTemplate('show');
  }
  
  public function executeShowMinimumList(sfWebRequest $request) {
      $this->setLayout(false);
      $this->materials = PartTable::findUnderMinimum();
      $this->version = 'minimum';
      $this->setTemplate('show');
  }  
  
  /**
   * Process all the purchases that have been received and adjust the stock
   * @param sfWebRequest $request 
   */
  public function executeBookPurchases(sfWebRequest $request) {
      foreach($_SESSION['clearinglist'] as $session){
          $id = $session['id'];
          //change the status of the purchase to received
          $purchase = PurchaseTable::getInstance()->findOneBy('id', $id);
          $purchase->setStatus('received');
          $purchase->save();
          //Adjust the stock of the material belonging to the purchase
          $amount = $session['amount'];
          $material = PartTable::getInstance()->findOneBy('id', $purchase->getMaterialId());
          $material->setStock($material->getStock() + $amount);
          $material->save();
          //Add a historyline to the material
          $historyLine = new MaterialHistory();
          $historyLine->setMaterialId($material->getId());
          $historyLine->setSupplier($session['supplier']);
          $historyLine->setReceived($amount);
          $historyLine->setPrice($session['price']);
          $historyLine->setStock($material->getStock());
          $historyLine->save();       
      }
      
      if(isset($_SESSION['clearinglist'])){
          unset($_SESSION['clearinglist']);
      }
      //Redirect to the index
      $this->redirect('purchase_index');
  }
  
  public function executeShowReceivedList(sfWebRequest $request) {
      $this->setLayout(false);
      $this->version = 'received';     
      $this->setTemplate('show');
  }
    
  public function executeFilterPurchase(sfWebRequest $request) {
        //display the results with the Symfony pager object.
        $this->filterPurchase = new PurchaseFormFilter;
        $this->filterPurchase->bind($request->getParameter($this->filterPurchase->getName()));
        $this->pagerPurchases = new sfDoctrinePager('Purchase', sfConfig::get('app_max_items_on_page'));
        $this->pagerPurchases->setQuery($this->filterPurchase->getQuery());
        $this->pagerPurchases->setPage($request->getParameter('pagepurchase', 1));
        $this->pagerPurchases->init();
      
        //Materials under minimum quantity pager
        $this->pagerMaterials = new sfDoctrinePager('Part', sfConfig::get('app_max_items_on_page'));
        $this->pagerMaterials->setQuery(PartTable::findUnderMinimumQuery());
        $this->pagerMaterials->setPage($request->getParameter('pagematerial', 1));
        $this->pagerMaterials->init();
        
        //refer back to the index template
        $this->setTemplate('index');
    }
    
    public function executeCreatePurchase(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));
        $this->form = new PurchaseForm();
        $this->processFormPurchase($request, $this->form);

        $this->setTemplate('new');
    }
    
    public function executeEditPurchase(sfWebRequest $request) {
        $this->forward404Unless($purchase = PurchaseTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->purchase = $purchase;
        $this->form = new PurchaseForm($purchase);
        
        $this->setTemplate('edit');
    }
    
    public function executeUpdatePurchase(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($purchase = PurchaseTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->form = new PurchaseForm($purchase);
        $this->processFormPurchaseEdit($request, $this->form);

        $this->setTemplate('edit');
    }
    
    //Unused function because there is no delete button
    public function executeDeletePurchase(sfWebRequest $request) {
        $request->checkCSRFProtection();
        $this->forward404Unless($purchase = PurchaseTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object product does not exist (%s).', $request->getParameter('id')));
        $purchase->delete();

        //Purchases
        $this->pagerPurchases = new sfDoctrinePager('Purchase', sfConfig::get('app_max_items_on_page'));
        $this->pagerPurchases->setQuery(PurchaseTable::getOrderedPurchases());
        $this->pagerPurchases->setPage($request->getParameter('pagepurchase', 1));
        $this->pagerPurchases->init();
        
        //materials
        $this->pagerMaterials = new sfDoctrinePager('Part', sfConfig::get('app_max_items_on_page'));
        $this->pagerMaterials->setQuery(PartTable::findUnderMinimumQuery());
        $this->pagerMaterials->setPage($request->getParameter('pagematerial', 1));
        $this->pagerMaterials->init();
        
        //filter
        $this->filterPurchase = new PurchaseFormFilter;         
        
        $this->redirect('purchase_index');
    }
    
    /**
     * Save every purchase that has been added to the 'purchaselist' session and adjust the stock
     * @param sfWebRequest $request
     * @param sfForm $form 
     */
    protected function processFormPurchase(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));                    
            if (isset($_SESSION['purchaselist'])){
                foreach($_SESSION['purchaselist'] as $session){  
                    //Create new purchase and retrieve all the variables from the session
                    $purchase= new Purchase();
                    $id = $session['id'];
                    $purchase->setMaterialId($id);
                    $amount = $session['amount'];
                    $purchase->setAmount($amount);
                    $price = $session['price'];
                    $purchase->setPrice($price);
                    $supplier = $session['supplier'];
                    $supplierName = null;
                    if($supplier != null){
                        $purchase->setSupplierId($supplier);
                        $supplierObject = ContactTable::getInstance()->findOneBy('id', $supplier);
                        $supplierName = $supplierObject->getName();
                    }
                    $status = $session['status'];
                    $purchase->setStatus($status);
                    
                    //If status is set to 'received' add the amount bought to the stock and save the action in the material history
                    if($status == 'received'){ 
                        $amount = $purchase->getAmount();
                        $part = PartTable::getInstance()->findOneBy('id', $purchase->getMaterialId());
                        $part->setStock($part->getStock() + $amount);
                        $part->save();

                        $historyLine = new MaterialHistory();
                        $historyLine->setMaterialId($part->getId());
                        $historyLine->setReceived($amount);
                        $historyLine->setPrice($price);
                        $historyLine->setSupplier($supplierName);
                        $historyLine->setStock($part->getStock());
                        $historyLine->save();
                    }
                    //Save the purchase to the database
                    $purchase->save();
                } 
            }
            unset($_SESSION['purchaselist']);
            
            //Redirect to the index
            $this->redirect('purchase_index');
    }
    
    protected function processFormPurchaseEdit(sfWebRequest $request, sfForm $form){
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $purchase = $form->save();      
            $supplier = $_POST['supplier'];

            //When status changes into 'received' the amount of the material bought is added to the stock
            if($purchase->getStatus() == 'received'){
                $amount = $purchase->getAmount();
                $price = $purchase->getPrice();
                $part = PartTable::getInstance()->findOneBy('id', $purchase->getMaterialId());
                $part->setStock($part->getStock() + $amount);
                $part->save();
                
                $historyLine = new MaterialHistory();
                $historyLine->setMaterialId($part->getId());
                $historyLine->setReceived($amount);
                $historyLine->setPrice($price);
                $historyLine->setStock($part->getStock());
                $historyLine->save();
            }

            $purchase->setSupplierId($supplier);
            $purchase->save();
              
            //Redirect to the index
            $this->redirect('purchase_index');
        }
    }
}
